package com.dayu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.dayu.common.constant.AuthServerConstant;
import com.dayu.common.exception.BizCodeEnum;
import com.dayu.common.utils.R;
import com.dayu.common.vo.MemberResponseVo;
import com.dayu.gulimall.auth.feign.MemberFeignService;
import com.dayu.gulimall.auth.feign.ThirdPartFeignService;
import com.dayu.gulimall.auth.vo.UserLoginVo;
import com.dayu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2021/3/9 21:54
 * @description
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendSms(@RequestParam("phone") String phone) {
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String code = UUID.randomUUID().toString().substring(0, 5);


        //1、接口防刷
        String smsCode = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(smsCode)) {
            String s = smsCode.split("_")[1];
            if (System.currentTimeMillis() - Long.valueOf(s) < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
//        2、验证码的再次校验，redis，存key-phone,value
        String str = code + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(key, str, 10, TimeUnit.MINUTES);

        System.out.println("code==="+code);

//        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    /**
     * RedirectAttributes redirectAttributes 模拟重定向携带数据，
     * 设置addFlashAttribute，取出一次就失效。保证的数据的有效性
     *, Model model
     * @param userRegistVo
     * @param bindingResult
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        /**
         * 前端校验，将错误信息收集并返回
         *
         */
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
//            model.addAttribute("errors", errors);
            // Request method 'POST' not supported
            //用户注册->/regist[post]  ---->转发/reg.html（路径映射默认都是get方式访问的）
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //真正的注册。调用远程注册服务
        //1、校验验证码
        String code = userRegistVo.getCode();
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone();
        String s = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(s)) {
            String codeSession = s.split("_")[0];
            if (code.equals(codeSession)) {
                //验证码相同，验证通过,删除验证码，令牌机制
                stringRedisTemplate.delete(key);
                //真正的远程调用，注册用户
                R r = memberFeignService.regist(userRegistVo);
                if (r.getCode() == 0) {
                    //注册成功 //注册成功，回到首页。回到登录页面
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,HttpSession session){
        R r = memberFeignService.login(vo);
        if (r.getCode()==0){
            MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
            });
            //1、默认发的令牌。session=xxxx.作用域：当前域：（解决子域session共享的问题）
            //2、使用JSON的序列化方式来序列化对象数据到redis中

            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
